package com.dpp.config;

import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.cert.CertificatesManager;
import com.wechat.pay.contrib.apache.httpclient.exception.HttpCodeException;
import com.wechat.pay.contrib.apache.httpclient.exception.NotFoundException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;

@Configuration
public class WxHttpRequest {

    @Resource
    WxInformation wxInformation;


    //获取证书管理器实例
    @Bean
    public CertificatesManager getVerifier() throws GeneralSecurityException, IOException, HttpCodeException {
        // 获取证书管理器实例
        CertificatesManager certificatesManager = CertificatesManager.getInstance();
       // 向证书管理器增加需要自动更新平台证书的商户信息
        certificatesManager.putMerchant(wxInformation.getMchId() , new WechatPay2Credentials(wxInformation.getMchId(),
                new PrivateKeySigner(wxInformation.getMchSerialNo(), wxInformation.getPrivateKey(wxInformation.getPrivateKeyPath()))), wxInformation.getV3Key().getBytes(StandardCharsets.UTF_8));
        return certificatesManager;
    }

    /**
     *  获取httpClicent请求对象
     * @param certificatesManager
     * @return  返回httpClient
     * @throws NotFoundException
     */
    @Bean
    public CloseableHttpClient sendWX(CertificatesManager certificatesManager) throws NotFoundException {


       // 从证书管理器中获取verifier
        Verifier verifier = certificatesManager.getVerifier(wxInformation.getMchId());
        WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create()
                .withMerchant(wxInformation.getMchId(), wxInformation.getMchSerialNo(), wxInformation.getPrivateKey(wxInformation.getPrivateKeyPath()))
                .withValidator(new WechatPay2Validator(verifier));
          // ... 接下来，你仍然可以通过builder设置各种参数，来配置你的HttpClient
        // 通过WechatPayHttpClientBuilder构造的HttpClient，会自动的处理签名和验签，并进行证书自动更新
        CloseableHttpClient httpClient = builder.build();
         return httpClient;
    }



}
